package com.itqf.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;

import java.util.Scanner;

/**
 * projectName: rbacgp8
 *
 * @author: 赵伟风
 * time: 2021/8/13 15:36
 * description:
 */
public class AuthenticationDemo {

    public static void main(String[] args) {


        IniSecurityManagerFactory factory = new IniSecurityManagerFactory("classpath:shiro.ini");

        SecurityManager securityManager = factory.getInstance();

        SecurityUtils.setSecurityManager(securityManager);

        Subject subject = SecurityUtils.getSubject();


        Scanner scanner = new Scanner(System.in);

        System.out.println("输入用户名");

        String username = scanner.nextLine();

        System.out.println("输入密码");

        String password = scanner.nextLine();


        UsernamePasswordToken token = new UsernamePasswordToken(username, password);


        try {
            subject.login(token);
            System.out.println("认证成功");
        }catch (AuthenticationException e){
            System.out.println("认证失败::"+e.getMessage());
        }

        /***
         * 是 认证方法返回的第一个参数!
         */
        Object principal = subject.getPrincipal();

        System.out.println("principal = " + principal);

        //user存到 session

        //授权
        boolean permitted = subject.isPermitted("class:info");

        System.out.println("permitted = " + permitted);


        boolean permitted1 = subject.isPermitted("admin:a");
        System.out.println("permitted1 = " + permitted1);


        boolean isSuper =  subject.hasRole("super");
        System.out.println("isSuper = " + isSuper);


    }
}
